package com.sky.module.system.utils;

import com.sky.module.system.user.domain.entity.User;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/***
 * @description 主要是获取 user 和  useragent 和和ip
 * @param null
 * @return
 * @date 2023/3/9 1:06
 *
 */
public class RequestInfoUtils {

    public static String getUserAgent() {
        HttpServletRequest request = getRequest();
        UserAgent userAgent = new UserAgent(request.getHeader("User-Agent"));
        return userAgent.toString();
    }

    private static HttpServletRequest getRequest() {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        return request;
    }

    public static String getIP() {
        HttpServletRequest request = getRequest();
        String ipAddress = IpUtil.getIpAddress(request);
        return ipAddress;
    }

    public static User getUser() {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return user;
    }
}
